//
//  YTTRunmapController.m
//  跑圈儿
//
//  Created by 唐康 on 16/4/19.
//  Copyright © 2016年 唐康. All rights reserved.
//

#import "YTTRunmapController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#define APIKey      @"261035312ed64f842e7f1f42970c54c9"
#import <Masonry.h>
#import "YTTControlStage.h"
//记录开始跑步与否 记录画线还是不画线
typedef  enum
{
    TrailStart = 1,
    TrailEnd
    
}Trail;

@interface YTTRunmapController ()<MAMapViewDelegate, AMapSearchDelegate>
{
    MAMapView *_mapView;
    AMapSearchAPI *_search;
    CLLocation *_currentLocation;
    UIButton *_locationButton;
    UIButton *_startBtn;
    UIButton *_stopBtn;
    
    //轨迹
    
    //上一个位置
    CLLocation *preLocation;
    //总距离
    double sumDistance;
    /**控制开始还是没开始跑步的属性*/
    
    Trail trail;
    NSMutableArray * _speedColors;
    CLLocationCoordinate2D * _runningCoords;
    NSUInteger _count;
    
    MAMultiPolyline * _polyline;
    
    
    //计时时间
     dispatch_source_t timer;
    
    
    //进入后台的date
    NSDate * goBackgroundDate;
    
}

/**< 坐标数组  */
@property(nonatomic, strong)NSMutableArray *locationArrayM;
/**< <#注释#>  */
@property(nonatomic, assign)Trail trail;

/**< 提示  */
@property(nonatomic, strong)YTTControlStage *cs;


@property(nonatomic, strong)UILabel *timeLable;/**< 计时lable */

/**< 是否开始 */
@property (nonatomic) BOOL isStart;

/**< 暂停 */
@property (nonatomic) BOOL isPause;


@property (nonatomic) BOOL isClick;
@property (nonatomic ,assign) BOOL isSelect;


@property (nonatomic,assign) int timeCount;
@property(nonatomic, strong)  UILabel *distance;


@end

@implementation YTTRunmapController
- (NSMutableArray *)locationArrayM
{
    if(_locationArrayM == nil){
        _locationArrayM = [NSMutableArray array];
    }
    return _locationArrayM;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor yellowColor];
    [self initMapView];
    [self initSearch];
    [self initControls];
    self.trail = TrailEnd;
    [self initStartBtn];
    [self initStopBtn];
    [self creatTimeViewAndLalbe];
   
    
    self.cs = [YTTControlStage ControlStage];
    [self.cs.continueRun addTarget:self action:@selector(continueAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.cs.completeRun addTarget:self action:@selector(completeAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:self.cs];
   // cs.backgroundColor = [UIColor yellowColor];
    [self.cs mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(YTTScreenW,80));
        make.bottom.mas_equalTo(self.view.mas_bottom).with.offset(- 40);
    }];
    self.cs.hidden = YES;
    
    
    
    
    
}

////进入后台
//-(void)viewWillAppear:(BOOL)animated
//{
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appGoBackground) name:@"程序进入后台" object:nil];
//    
//    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appGoForeground) name:@"程序进入前台" object:nil];
//    
//}
//
//-(void)appGoBackground
//{
//    
//    goBackgroundDate = [NSDate date];
//    
//}
//
//
//-(void)appGoForeground
//{
//
//    NSTimeInterval timeGone = [[NSDate date] timeIntervalSinceDate:goBackgroundDate];
//    
//  
//    
//}
//









-(void)creatTimeViewAndLalbe{
    
    
    //创建计时View
    UIView *timeView = [[UIView alloc] initWithFrame:CGRectMake(20, 84, YTTScreenW - 40, 150)];
    timeView.backgroundColor = [UIColor whiteColor];
    timeView.layer.cornerRadius = 5;
    [self.view addSubview:timeView];
    
    
    //分割线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 86, YTTScreenW - 60, 1)];
    lineView.backgroundColor =[ UIColor lightGrayColor];
    [timeView addSubview:lineView];
    
    
    //创建计时lable
    self.timeLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, YTTScreenW - 80, 85)];
    self.timeLable.backgroundColor = [UIColor whiteColor];
    [timeView addSubview:self.timeLable];
    self.timeLable.text = @"00:00:00";
    self.timeLable.textColor = [UIColor colorWithRed:76 / 255.0 green:145 / 255.0 blue:235 / 255.0 alpha:0.9];
    self.timeLable.font = [UIFont systemFontOfSize:50 weight:0.5];
    self.timeLable.textAlignment = NSTextAlignmentCenter;
    
    //距离(km)lable
    UILabel *distanceLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 87, 100, 25)];
    distanceLable.backgroundColor = [UIColor clearColor];
    [timeView addSubview:distanceLable];
    distanceLable.text = @"距离(km)";
    distanceLable.textColor = [UIColor colorWithRed:76 / 255.0 green:145 / 255.0 blue:235 / 255.0 alpha:0.9];
    distanceLable.textAlignment = NSTextAlignmentCenter;
    distanceLable.font = [UIFont systemFontOfSize:15];
    
    //距离lable
    self.distance = [[UILabel alloc] initWithFrame:CGRectMake(20, 116, 100, 35)];
    self.distance.backgroundColor = [UIColor clearColor];
      [timeView addSubview:self.distance];
    self.distance.textAlignment = NSTextAlignmentCenter;
    self.distance.font = [UIFont systemFontOfSize:16 weight:0.5];
    
    //卡路里
    UILabel *kcalLable = [[UILabel alloc] initWithFrame:CGRectMake(self.timeLable.frame.origin.x + 150, 87, 100, 25)];
    kcalLable.backgroundColor = [UIColor clearColor];
    [timeView addSubview:kcalLable];
    kcalLable.text = @"卡路里(kcal)";
    kcalLable.textColor = [UIColor colorWithRed:76 / 255.0 green:145 / 255.0 blue:235 / 255.0 alpha:0.9];
    kcalLable.textAlignment = NSTextAlignmentCenter;
    kcalLable.font = [UIFont systemFontOfSize:15];
    
    
    UILabel *kcal = [[UILabel alloc] initWithFrame:CGRectMake(200, 116, 100, 35)];
    kcal.backgroundColor = [UIColor clearColor];
    kcal.textAlignment = NSTextAlignmentCenter;
    [timeView addSubview:kcal];
    
    
    

    
}



- (void)continueAction{
    
    YTTLog(@"继续");
    self.cs.hidden = YES;
    [self setTrail];
   
}

- (void)completeAction{
    
    dispatch_resume(timer);
    dispatch_source_cancel(timer);
    _isPause = NO;
    
    YTTLog(@"完成");
    [self.locationArrayM removeAllObjects];
    
    //将数据存入数据库
    
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *str = self.timeLable.text;
    NSString *dateStr = [dateFormatter stringFromDate:[NSDate date]];
    
    NSDate *dateInsert = [NSDate date];
    NSString * insertStr = [NSString stringWithFormat:@"%ld",(long)[dateInsert timeIntervalSince1970]];
    
    [[YTTDataManager shareInstance] insertMiter:(sumDistance / 1000.0) Time:str Calendar:dateStr TimeStamp:insertStr];
    [[YTTDataManager shareInstance ] delegateData];
    
    
    [_mapView removeOverlay:_polyline];
    _polyline = nil;
    
    _timeCount = 0;
    
 self.cs.hidden = YES;
    _stopBtn.hidden = YES;
    _startBtn.hidden = NO;
}







//stop btn
/**< 停止的button */
- (void)initStopBtn{
    _mapView.showsUserLocation = NO;
    _stopBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_mapView addSubview:_stopBtn];
    [_stopBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(80, 40));
        make.bottom.mas_equalTo(_mapView.mas_bottom).with.offset(-80);
        make.centerX.mas_equalTo(_mapView.mas_centerX);
    }];
    
    _stopBtn.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    [_stopBtn setTitle:@"停止跑步" forState:(UIControlStateNormal)];
    [_stopBtn setBackgroundColor:[UIColor cyanColor]];
    _stopBtn.layer.cornerRadius = 5;
    [_stopBtn addTarget:self action:@selector(stopRun) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    
   
    
}


- (void)stopRun{
    
    self.trail = TrailEnd;
    //暂停时间
    dispatch_suspend(timer);
    _isPause = YES;
   
  
    
    self.tabBarController.tabBar.hidden = NO;
    //    [UIView animateWithDuration:3 animations:^{
    //        self.tabBarController.tabBar.hidden = no;
    //
    //    }];
    
    
    [UIView animateWithDuration:0.5 animations:^{
        self.cs.hidden = NO;
        
    }];
    
    
}

//开始跑步按钮
- (void)initStartBtn{
    _startBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.view addSubview:_startBtn];
    [_startBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(80, 40));
        make.bottom.mas_equalTo(_mapView.mas_bottom).with.offset(- 80);
        make.centerX.mas_equalTo(_mapView.mas_centerX);
    }];
    
    _startBtn.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    _startBtn.backgroundColor = [UIColor yellowColor];
    [_startBtn setTitle:@"开始" forState:(UIControlStateNormal)];
    _startBtn.layer.cornerRadius = 5;
    [_startBtn addTarget:self action:@selector(setTrail) forControlEvents:(UIControlEventTouchUpInside)];


    
}


    
//开始并开始记步0

-(void)startToCoutTime
{
    if ([_startBtn.titleLabel.text isEqualToString:@"开始"]) {
        if (timer && _isPause == YES) {
            dispatch_resume(timer);
        }
        dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, globalQueue);
        
    }
    
    //    每秒执行一次
    dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), 1.0 *NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(timer, ^{
        int hours = _timeCount / 3600;
        int minutes = (_timeCount - (3600 * hours)) / 60;
        int seconds = _timeCount % 60;
        NSString *strTime = [NSString stringWithFormat:@"%.2d:%.2d:%.2d",hours,minutes,seconds];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //           ======在这根据自己的需求去刷新UI==============
            _timeLable.text = strTime;
            
        });
        _timeCount ++;
    });
    
    dispatch_resume(timer);
    _isPause = NO;
    
    
}

- (void)setTrail{
    
    self.trail = TrailStart;
    [self startToCoutTime];
    [UIView animateWithDuration:3 animations:^{
        
        self.tabBarController.tabBar.hidden = YES;
        
    }];
    
    _startBtn.hidden = YES;
    _stopBtn.hidden = NO;
    
    
}

- (void)initMapView
{
    [MAMapServices sharedServices].apiKey = APIKey;
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
    
    _mapView.delegate = self;
    _mapView.compassOrigin = CGPointMake(_mapView.compassOrigin.x, 22);
    _mapView.scaleOrigin = CGPointMake(_mapView.scaleOrigin.x, 22);
    
    [self.view addSubview:_mapView];
    
    
}

- (void)initSearch
{
    [AMapSearchServices sharedServices].apiKey = APIKey;
    //    _search = [[AMapSearchAPI alloc] initWithSearchKey:APIKey Delegate:self];
    _search = [[AMapSearchAPI alloc]init];
    _search.delegate = self;
    
}

- (void)initControls
{
    _locationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_mapView addSubview:_locationButton];
 
    _locationButton.frame = CGRectMake(20, CGRectGetHeight(_mapView.bounds) - 110, 40, 40);
    _locationButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
   _locationButton.backgroundColor = [UIColor whiteColor];
    _locationButton.layer.cornerRadius = 5;
    
    [_locationButton addTarget:self action:@selector(locateAction) forControlEvents:UIControlEventTouchUpInside];
   [_locationButton setImage:[UIImage imageNamed:@"locate"] forState:(UIControlStateNormal)];
   // [_locationButton setImage:[UIImage imageNamed:@"locate_click"] forState:(UIControlStateNormal)];
    // [_locationButton setImage:[UIImage imageNamed:@"location_no"] forState:UIControlStateNormal];
    
}



#pragma mark - Helpers

- (void)locateAction
{
    _mapView.showsUserLocation = YES;
    
    if (_mapView.userTrackingMode != MAUserTrackingModeFollow)
    {
        [_mapView setUserTrackingMode:MAUserTrackingModeFollowWithHeading animated:YES];
    }
    
    //判断点击状态
    if (!_isClick) {
        [_locationButton setImage:[UIImage imageNamed:@"locate"] forState:(UIControlStateNormal)];

    }else{
        
        [_locationButton setImage:[UIImage imageNamed:@"locate_click"] forState:(UIControlStateNormal)];
        
    }
    
    _isClick = !_isClick;
    
    
    
    
}

- (void)reGeoAction
{
    if (_currentLocation)
    {
        AMapReGeocodeSearchRequest *request = [[AMapReGeocodeSearchRequest alloc] init];
        
        request.location = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude];
        
        [_search AMapReGoecodeSearch:request];
    }
}

#pragma mark - AMapSearchDelegate

- (void)searchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"request :%@, error :%@", request, error);
}

- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    NSLog(@"response :%@", response);
    
    NSString *title = response.regeocode.addressComponent.city;
    if (title.length == 0)
    {
        title = response.regeocode.addressComponent.province;
    }
    
    _mapView.userLocation.title = title;
    _mapView.userLocation.subtitle = response.regeocode.formattedAddress;
    
}

#pragma mark - MAMapViewDelegate

- (void)mapView:(MAMapView *)mapView didChangeUserTrackingMode:(MAUserTrackingMode)mode animated:(BOOL)animated
{
    // 修改定位按钮状态
    if (mode == MAUserTrackingModeNone)
    {
        [_locationButton setImage:[UIImage imageNamed:@"location_no"] forState:UIControlStateNormal];
    }
    else
    {
        [_locationButton setImage:[UIImage imageNamed:@"location_yes"] forState:UIControlStateNormal];
    }
}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    // NSLog(@"%@",userLocation.location);
    _currentLocation = [userLocation.location copy];
    if (self.trail == TrailEnd) {
        // MACoordinateRegion adjustRegion =[_mapView regionThatFits:(MACoordinateRegionMake(userLocation.location.coordinate, MACoordinateSpanMake(0.002, 0.002)))];
        
        // [_mapView setRegion:adjustRegion animated:YES];
        //MACoordinateRegion adjustResion2 = [_mapView regionThatFits:adjustRegion];
    }
    /** 判断用户是否在户外 */
    if (userLocation.location.horizontalAccuracy > kCLLocationAccuracyNearestTenMeters) {
        return;
    }
    /** 开始运动 */
    if(self.trail == TrailStart){
        // 开始用户路径跟踪
        [self startTrailRouterWithUserLocation:userLocation];
        [_mapView setRegion:MACoordinateRegionMake(userLocation.location.coordinate, MACoordinateSpanMake(0.002, 0.002)) animated:YES];
    }
    
    //记录距离
    NSString *str = [NSString stringWithFormat:@"%.2f",sumDistance/ 1000.0];
    self.distance.text = str;

    
    //计算卡路里
    
    YTTLog(@"行程为%.2fKM",sumDistance / 1000.0);
    
}
-(void)startTrailRouterWithUserLocation:(MAUserLocation *)userLocation{
    /*计算当前点 和前一个点的距离*/
    if (preLocation) {
        double distance = [userLocation.location distanceFromLocation:preLocation];
        sumDistance += distance;
    }
    
    preLocation = userLocation.location;
    //把用当前位置当如数组中
    [self.locationArrayM addObject:userLocation.location];
    //绘制路线
    [self drawWalkLine];
    
    
    
}

- (void)drawWalkLine{
    NSInteger count = self.locationArrayM.count;
    MAMapPoint *points = malloc(sizeof(MAMapPoint)*count);
    [self.locationArrayM enumerateObjectsUsingBlock:^(CLLocation* obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MAMapPoint point = MAMapPointForCoordinate(obj.coordinate);
        points[idx] = point;
    }];
    if (_polyline) {
        
        [_mapView removeOverlay:_polyline];
    }
    _polyline = [MAMultiPolyline polylineWithPoints:points count:count];
    
    [_mapView addOverlay:_polyline];
    free(points);
}


- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    if (overlay == _polyline)
    {
        MAMultiColoredPolylineRenderer * polylineRenderer = [[MAMultiColoredPolylineRenderer alloc] initWithMultiPolyline:overlay];
        
        polylineRenderer.lineWidth = 8.f;
        polylineRenderer.strokeColors = _speedColors;
        polylineRenderer.gradient = YES;
        
        return polylineRenderer;
        
    }
    
    return nil;
}


- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view
{
    // 选中定位annotation的时候进行逆地理编码查询
    if ([view.annotation isKindOfClass:[MAUserLocation class]])
    {
        [self reGeoAction];
    }
}


/**< 
 
        笔记
 1.dispatch_source_create
 
 创建一个新的调度源来监视低级别的系统对象和自动提交处理程序块来响应事件调度队列
 (dispatch_queue_t myQueue = dispatch_queue_create("com.iphonedevblog.post", NULL);其中，第一个参数是标识队列的，第二个参数是用来定义队列的参数（目前不支持，因此传入NULL）)
 
 2.dispatch_source_set_timer
 
 为一个定时源设置一个开始时间、事件间隔、误差值 
 3.dispatch_source_set_event_handler
 
 给一个调度源设置一个时间处理块。
 
 4.dispatch_source_cancel
 
 异步取消一个调度源，防止任何进一步调用它的事件处理块的发生
 
 5.dispatch_source_set_cancel_handler
 
 给一个调度源设置一个取消处理块
 
 6.dispatch_resume
 
 7.dispatch_source_cancel 
 
 在执行之前timer必须是执行状态
 
 GCD提供很多超越传统多线程编程的优势：
 
 易用: GCD比之thread跟简单易用。由于GCD基于work unit而非像thread那样基于运算，所以GCD可以控制诸如等待任务结束、监视文件描述符、周期执行代码以及工作挂起等任务。基于block的血统导致它能极为简单得在不同代码作用域之间传递上下文。
 效率: GCD被实现得如此轻量和优雅，使得它在很多地方比之专门创建消耗资源的线程更实用且快速。这关系到易用性：导致GCD易用的原因有一部分在于你可以不用担心太多的效率问题而仅仅使用它就行了。
 性能: GCD自动根据系统负载来增减线程数量，这就减少了上下午切换以及增加了计算效率。
 
*/

@end
